<template>
  <div class="query-container">
    <el-card shadow="never">
      <template #header>
        <div class="query-header">
          <span>停车记录查询</span>
          <el-button
              type="primary"
              @click="exportData"
              :loading="exportLoading"
          >
            导出数据
          </el-button>
        </div>
      </template>

      <el-form :model="queryForm" inline>
        <el-form-item label="车牌号">
          <el-input
              v-model="queryForm.plate_number"
              placeholder="请输入完整车牌号"
              clearable
          />
        </el-form-item>

        <el-form-item label="入库时间">
          <el-date-picker
              v-model="queryForm.entryRange"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="出库状态">
          <el-select v-model="queryForm.has_exit" clearable>
            <el-option label="已出库" value="true"/>
            <el-option label="未出库" value="false"/>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table
          :data="tableData"
          v-loading="loading"
          stripe
          style="width: 100%"
      >
        <el-table-column prop="plate_number" label="车牌号" fixed width="150"/>
        <el-table-column label="入库时间" width="180">
          <template #default="{row}">
            {{ formatTime(row.entry_time) }}
          </template>
        </el-table-column>
        <el-table-column label="出库时间" width="180">
          <template #default="{row}">
            {{ row.exit_time ? formatTime(row.exit_time) : '--' }}
          </template>
        </el-table-column>
        <el-table-column label="置信度" width="100">
          <template #default="{row}">
            <el-progress
                :percentage="row.confidence * 100"
                :format="() => `${(row.confidence * 100).toFixed(1)}%`"
                :stroke-width="15"
                status="success"
            />
          </template>
        </el-table-column>
        <el-table-column label="应付金额">
          <template #default="{row}">
            <el-tag :type="row.amount_due > 0 ? 'danger' : 'success'">
              {{ row.amount_due }}元
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          :total="pagination.total"
          @size-change="handleSearch"
          @current-change="handleSearch"
      />
    </el-card>

  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import api from '@/api'
import {formatTime} from '@/utils/format'
import HourlyChart from '@/components/HourlyChart.vue';

const loading = ref(false)
const tableData = ref([])
const queryForm = ref({
  plate_number: '',
  entryRange: [],
  has_exit: ''
})
const pagination = ref({
  current: 1,
  size: 10,
  total: 0
})

const handleSearch = async () => {
  loading.value = true
  try {
    const params = {
      ...queryForm.value,
      page: pagination.value.current,
      per_page: pagination.value.size
    }

    if (queryForm.value.entryRange) {
      params.start_entry_time = queryForm.value.entryRange[0]
      params.end_entry_time = queryForm.value.entryRange[1]
    }

    const res = await api.getRecords(params)
    tableData.value = res.data.data
    pagination.value.total = res.data.pagination.total
  } catch (error) {
    ElMessage.error('查询失败')
  } finally {
    loading.value = false
  }
}

// 导出数据相关
const exportLoading = ref(false)

const exportData = async () => {
  exportLoading.value = true
  try {
    // 组织请求参数（排除分页参数）
    const params = {
      ...queryForm.value,
      page: undefined,
      per_page: undefined
    }

    // 处理时间范围参数
    if (queryForm.value.entryRange?.length === 2) {
      params.start_entry_time = queryForm.value.entryRange[0]
      params.end_entry_time = queryForm.value.entryRange[1]
    }


    // 修改请求配置
    const res = await api.exportRecords(params, {
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      }
    })

    // 修复1：指定Blob类型
    const blob = new Blob([res.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })

    // 修复2：安全获取文件名
    const filenameHeader = res.headers['content-disposition']
    const filename = filenameHeader
      ? decodeURIComponent(filenameHeader.split('filename=')[1])
      : `停车记录_${new Date().toISOString().slice(0,10)}.xlsx`

    // 修复3：创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename.replace(/"/g, '') // 移除可能存在的引号
    document.body.appendChild(link)
    link.click()

    // 修复4：延迟清理资源
    setTimeout(() => {
      window.URL.revokeObjectURL(url)
      link.remove()
    }, 100)

    ElMessage.success('导出成功，文件已开始下载')

  } catch (error) {
    // 增强错误处理
    if (error.response?.headers['content-type']?.includes('json')) {
      const reader = new FileReader()
      reader.onload = () => {
        try {
          const errData = JSON.parse(reader.result)
          ElMessage.error(`导出失败：${errData.message}`)
        } catch {
          ElMessage.error('服务器返回了未知格式的错误信息')
        }
      }
      reader.readAsText(error.response.data)
    } else {
      ElMessage.error(`导出失败：${error.message}`)
    }
  } finally {
    exportLoading.value = false
  }
}

onMounted(() => {
  handleSearch()
})
</script>

<style scoped>
.query-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.query-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>